package com.yyhh.helpcall.http.interceptor;

import android.content.Intent;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import com.yyhh.helpcall.MainApplication;
import com.yyhh.helpcall.activity.MainActivity;
import com.yyhh.helpcall.utils.NetLog;
import com.yyhh.helpcall.utils.ToastUtils;
import java.io.IOException;
import okhttp3.Interceptor;
import okhttp3.Response;

public class AuthInterceptor implements Interceptor {

    private Handler handler = new Handler(Looper.getMainLooper()){
        @Override
        public void handleMessage(Message msg) {
            if(msg.what == 401){
                if(MainApplication.mainApplication != null){
                    try {
                        ToastUtils.show("用户已过期,请重新登录");
                        Intent intent = new Intent(MainApplication.mainApplication, MainActivity.class);
                        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        intent.putExtra("isLoginOut",true);
                        MainApplication.mainApplication.startActivity(intent);
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }
            }
        }
    };

    @Override
    public Response intercept(Chain chain) throws IOException {
        Response response = chain.proceed(chain.request());
        if(response.code() == 412 || response.code() == 413){
            //token 失效
            Message obtain = Message.obtain();
            obtain.what = 401;
            handler.sendMessage(obtain);
        }
        NetLog.d("AuthInterceptor " + response.request().url().toString());
        return response;
    }
}
